package com.linkoog.devtools.code_generator.wizard.generate.database.template.tree;

import javax.swing.*;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * 复选框树形节点鼠标点击监听事件
 */
public class CheckBoxTreeNodeSelectionListener extends MouseAdapter {

    /**
     * 默认 checkbox 宽度
     */
    int checkboxWidth = 12;

    @Override
    public void mouseClicked(MouseEvent event) {
        JTree tree = (JTree) event.getSource();
        int row = tree.getRowForLocation(event.getX(), event.getY());
        tree.setSelectionRow(row);
        TreePath path = tree.getPathForRow(row);
        if (path == null) {
            return;
        }

        if(event.getX() > tree.getPathBounds(path).x + checkboxWidth ){
            return;
        }




        if (SwingUtilities.isLeftMouseButton(event)) {
            if (!isDoubleClick(event)) {
                //鼠标左键--单击
                CheckBoxTreeNode node = (CheckBoxTreeNode) path.getLastPathComponent();
                if (node != null) {
                    boolean isSelected = !node.isSelected();
                    node.setSelected(isSelected);
                    ((DefaultTreeModel) tree.getModel()).nodeStructureChanged(node);
                }
            } else {

            }
        }
    }

    public static boolean isDoubleClick(MouseEvent e) {
        return e != null && e.getClickCount() > 0 && e.getClickCount() % 2 == 0;
    }


}
